//
//  WBNetWorkManager+Extension.swift
//  weibo
//
//  Created by iobit on 2017/06/28.
//  Copyright © 2017 zhuxu. All rights reserved.
//

import Foundation

extension WBNetWorkManager {

    /// 加载微博数据字典数组
    ///
    /// - Parameters:
    ///   - since_id: 返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0
    ///   - max_id: 返回ID小于或等于max_id的微博，默认为0
    ///   - completion: 完成回调[status: 微博字典数组/是否成功]
    func statusList(since_id: Int64 = 0, max_id: Int64 = 0, completion: @escaping (_ statusList: [[String: Any]], _ isSuccess:Bool)->()) {
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json" //获取当前登录用户及其所关注（授权）用户的最新微博
        
        let param = ["since_id": "\(since_id)",
            "max_id": "\(max_id > 0 ? max_id-1 : 0)"]
        
        tokenRequest(URLString: urlString, parameters: param) { (json, isSuccess) in
            
            let resultDit = json as? [String: Any]
            let list = resultDit?["statuses"] as? [[String: Any]]
            completion(list ?? [], isSuccess)
        }
    }
    
    
    func unreadCount(completion: @escaping (_ count : Int)->()) {
        
        guard let uid = userAccount.uid else {
            completion(0)
            return
        }
        
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        let param = ["uid": uid]
        
        tokenRequest(URLString: urlString, parameters: param) { (json, isSuccess) in

            let jsonDic = json as? [String: Int]
            let count = jsonDic?["status"]
            completion(count ?? 0)
        }
    }
}



// MARK: - 获取用户信息头像和用户名
extension WBNetWorkManager {
    
    // 加载用户当前信息
    func loadUserInfo(completion: @escaping (_ dict: [String: Any])->()) {
        guard let uid = userAccount.uid else {
            return
        }
        let urlString = "https://api.weibo.com/2/users/show.json"
        let param = ["uid": uid]
        tokenRequest(URLString: urlString, parameters: param) { (json, isSuccess) in
            completion((json as? [String: Any]) ?? [:])
        }
    }
    
}


// MARK: - OAuth相关方法
extension WBNetWorkManager {
    // 加载AccessToke
    func loadAccessToken(code: String, completion: @escaping (_ isSuccess: Bool)->()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let param = ["client_id": WBAppKey,
                     "client_secret": WBAppSecret,
                     "grant_type": "authorization_code",
                     "code": code,
                     "redirect_uri": WBRedirectURI,
                     ]
        request(method: .POST, URLString: urlString, parameters: param) { (json, isSuccess) in
            // 需要在初始化单利时，设置响应反序列化支持的数据类型，否则会报错
            self.userAccount.yy_modelSet(with: (json as? [String: Any]) ?? [:])
    
            // 加载当前用户信息
            self.loadUserInfo(completion: { (dict) in
                
                self.userAccount.yy_modelSet(with: dict)
                
                print(self.userAccount)
                
                self.userAccount.saveAccount()
                
                //完成回调
                completion(isSuccess)
            })
            

        }
    }
    
    
}
